import { Alert, App, AutoComplete, Button, Input, InputNumber, Modal, Space } from 'antd';
import { useState, useEffect, useRef, useContext, useMemo } from 'react'
import BusinessMap from '../../common/BusinessMap';
import { Vector as VectorLayer } from 'ol/layer';
import { Vector as VectorSource } from 'ol/source';
import { Circle as CircleStyle, Fill, Style } from 'ol/style';
import { Point } from 'ol/geom';
import { Feature } from 'ol';
import { geomToWkt, wktToGeom } from '../../../utils/helper/mapHelper';
import managerContext from '../../modules/manager/Entry/managerContext';
import MapSearchApi from '../../../utils/apis/MapSearchApi';
import './index.less';

const MapLogic = props => {
    const { value, onChange } = props;
    const { map } = useContext(BusinessMap.Context);
    //要求获取经纬度信息
    const mContext = useContext(managerContext)
    const { setLongitudeAndLatitude } = mContext || {};
    const [_onChange] = useState(() => {
        return onChange;
    })

    const vectorLayer = useMemo(() => {
        if (map) {
            const layer = new VectorLayer({
                source: new VectorSource(),
                style: new Style({
                    image: new CircleStyle({
                        fill: new Fill({
                            color: '#0ff'
                        }),
                        radius: 8
                    })
                }),
                zIndex: 999
            });
            map.addLayer(layer);
            return layer;
        }
    }, [map])

    useEffect(() => {
        if (vectorLayer && value && map) {
            vectorLayer.getSource().clear();
            const point = wktToGeom(value);
            const feature = new Feature({
                geometry: point
            });
            vectorLayer.getSource().addFeature(feature)
            // map.getView().setCenter(point.getCoordinates())
        }
    }, [value, vectorLayer, map])
    useEffect(() => {
        if (map && vectorLayer) {
            const handler = (e) => {
                //console.log("标记51行",e)
                e.stopPropagation();
                //console.log("标记52行",e)
                //要求保留小数点后六位
                const roundedCoordinates = e.coordinate.map(coord => coord.toFixed(6));
                setLongitudeAndLatitude && setLongitudeAndLatitude(roundedCoordinates);
                const point = new Point(roundedCoordinates);
                //const point = new Point(e.coordinate);
                //console.log("标记53行",roundedCoordinates)
                //console.log("标记54行",point)
                const wkt = geomToWkt(point);
                //console.log("标记54行",wkt)
                _onChange(wkt)
            }
            map?.on('singleclick', handler);
            return () => {
                map.un('singleclick', handler);
            }
        }
    }, [map, vectorLayer, _onChange, setLongitudeAndLatitude])
    return null;
}

export default function MapPoint(props) {
    const { value, onChange } = props;
    const mapRef = useRef();
    const [open, setOpen] = useState();
    const [insideValue, setInsideValue] = useState();
    const [datas, setDatas] = useState([]);
    const [searching, setSearching] = useState()
    const { message } = App.useApp();

    const [lon, setLon] = useState();
    const [lat, setLat] = useState();
    useEffect(() => {
        setInsideValue(value);
    }, [value])
    return <>
        <Input value={value} onChange={e => {
            onChange(e.target.value)
        }} addonAfter={<Button type='link' size='small' onClick={e => {

            setOpen(true)
        }}>从地图上选择</Button>} />
        <Modal open={open} title={<div className='layout-h center'>
            <span>地图选点</span>

        </div>} width={800} bodyStyle={{
            height: 600,
            position: 'relative'
        }} onCancel={e => setOpen(false)} onOk={e => {
            onChange(insideValue)
            setOpen(false);
        }} className='map-point' >
            <div className='wh100 layout-v'>
                <div className='fill relative'>
                    <BusinessMap ref={mapRef} >
                        <MapLogic value={insideValue} onChange={v => {
                            setInsideValue(v)
                        }} />
                    </BusinessMap>
                    <div style={{
                        position: 'absolute',
                        top: 10,
                        right: 10,

                    }}>
                        <AutoComplete popupMatchSelectWidth={300}
                            style={{
                                width: 350,
                            }}
                            options={datas.map(d => {
                                return {
                                    label: <div className='layout-h center'>
                                        <div>{d['名称']}</div>
                                        <div style={{
                                            marginLeft: 10,
                                            color: '#ffffff99',
                                            fontSize: 12
                                        }}>{d['区县']}{d['地址']}</div>
                                    </div>,
                                    value: [d['X'], d['Y']]
                                }
                            })}
                            onSelect={value => {
                                console.log(value, mapRef)
                                if (value) {
                                    mapRef.current.map.getView().animate({ zoom: 18, center: value });
                                }
                            }}>
                            <Input.Search loading={searching} placeholder="输入关键字查询" enterButton
                                onSearch={value => {
                                    setSearching(true)
                                    MapSearchApi.search(value).then(resp => {
                                        if (resp.message?.features?.length > 0) {
                                            const datas = [];
                                            resp.message.features.forEach(feature => {
                                                const attrs = feature.attributes || [];
                                                const item = {};
                                                resp.message.columns.forEach((col, i) => {
                                                    item[col.columnName] = attrs[i];
                                                });
                                                datas.push(item);
                                            });
                                            setDatas(datas)
                                        }
                                    }).finally(e => { setSearching(false) });
                                }} />
                        </AutoComplete>
                    </div>

                    <div style={{
                        position: 'absolute',
                        top: 10,
                        left: 10,

                    }}>
                        <Space.Compact>
                            <InputNumber placeholder='经度' style={{ width: 120 }} value={lon} onChange={value => {
                                setLon(value)
                            }}></InputNumber>
                            <InputNumber placeholder='纬度' style={{ width: 120 }} value={lat} onChange={value => {
                                setLat(value);
                            }}></InputNumber>
                            <Button type="default" onClick={e => {
                                if (!lon) {
                                    message.error('请输入经度');
                                    return;
                                }
                                if (!lat) {
                                    message.error('请输入纬度');
                                    return;
                                }
                                if (lon < -180 || lon > 180) {
                                    message.error('无效的经度');
                                    return;
                                }
                                if (lat < -90 || lon > 90) {
                                    message.error('无效的纬度');
                                    return;
                                }
                                const point = [lon, lat];

                                mapRef.current.map.getView().animate({ zoom: 18, center: point });
                                setInsideValue(`POINT(${lon} ${lat})`);
                            }}>定位</Button>
                        </Space.Compact>
                    </div>
                </div>
            </div>
            <Alert type='error' message="点击地图选择目标点" style={{
                position: "absolute",
                bottom: -51
            }}></Alert>
        </Modal>
    </>;
}